package me.spring.cloud.components.starter.oauth2.princiapl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.security.oauth2.resource.FixedPrincipalExtractor;
import org.springframework.boot.autoconfigure.security.oauth2.resource.PrincipalExtractor;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author luffy
 */
@Slf4j
public class UserPrincipalExtractor implements PrincipalExtractor {

    private FixedPrincipalExtractor fixedPrincipalExtractor = new FixedPrincipalExtractor();

    @Override
    public Object extractPrincipal(Map<String, Object> map) {
        Map<String, Object> authentication = (Map<String, Object>) map.get("userAuthentication");
        if (authentication != null) {
            LinkedHashMap<String, Object> principal = (LinkedHashMap<String, Object>) authentication.get("principal");
            try {
                Object userInfo = principal.get("userInfo");
                return userInfo;
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                throw new InvalidTokenException("");
            }
        } else {
            Object principal = this.fixedPrincipalExtractor.extractPrincipal(map);
            return (principal == null ? "unknown" : principal);
        }
    }
}
